﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using admin.cyt369.com.Models;
using Admin.CYT369.Com.WebBase;

namespace admin.cyt369.com.Controllers
{
    public partial class AccountController
    {
        public UserManager<Admin.CYT369.Com.DAL.Domains.SysUser> UserManager { get; set; }
        public SignInManager<Admin.CYT369.Com.DAL.Domains.SysUser> SignInManager { get; set; }

        public AccountController(UserManager<Admin.CYT369.Com.DAL.Domains.SysUser> userManager, SignInManager<Admin.CYT369.Com.DAL.Domains.SysUser> signInManager)
        {
            this.UserManager = userManager;
            this.SignInManager = signInManager;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public virtual async Task<IActionResult> Login([FromForm]Admin.CYT369.Com.WebBase.AccountLogin user)
        {
            var retVal = new Admin.CYT369.Com.WebBase.ExecuteResult();

            if (user != null)
            {
                if (string.Compare(this.UserSession.CaptchaCode, user.Captcha, true) == 0)
                {
                    try
                    {
                        var loginUser = await this.UserManager.FindByNameAsync(user.LoginName);
                        if (loginUser != null)
                        {
                            if (loginUser.Enable)
                            {
                                if (loginUser.Deleted == false)
                                {
                                    var result = await this.SignInManager.PasswordSignInAsync(user.LoginName, user.Password, false, true);
                                    if (result.Succeeded)
                                    {
                                        // make session
                                        var userJson = System.Text.Json.JsonSerializer.Serialize(loginUser);
                                        this.HttpContext.Session.Set(Admin.CYT369.Com.Utility.ConstStringClass.SessionUser, System.Text.Encoding.UTF8.GetBytes(userJson));

                                        retVal.Result = true;
                                        return Redirect("~/Home/Index");
                                    }
                                    else if (result.IsLockedOut)
                                    {
                                        retVal.Msg = "用户被锁定";
                                    }
                                    else if (result.IsNotAllowed)
                                    {
                                        retVal.Msg = "用户未验证，不能登录";
                                    }
                                    else
                                    {
                                        retVal.Msg = "错误的用户名或密码";
                                    }
                                }
                                else
                                {
                                    retVal.Msg = "用户不存在";
                                }
                            }
                            else
                            {
                                retVal.Msg = "未开启登录权限";
                            }
                        }
                        else
                        {
                            retVal.Msg = "用户不存在";
                        }
                    }
                    catch (Microsoft.Data.SqlClient.SqlException ex)
                    {
                        if (ex.InnerException != null)
                        {
                            if (ex.InnerException.GetType() == typeof(System.ComponentModel.Win32Exception))
                            {
                                retVal.Msg = "无法连接 SQL Server 数据库服务";
                            }
                            else
                            {
                                retVal.Msg = string.Format("{0}", ex.Message);
                            }
                        }
                        else if (ex.Message != null && ex.Message.IndexOf("Could not open a connection to SQL Server") > 0)
                        {
                            retVal.Msg = "无法连接 SQL Server 数据库服务";
                        }
                        else
                        {
                            retVal.Msg = string.Format("{0}", ex.Message);
                        }
                    }
                    catch (Exception ex)
                    {
                        retVal.Msg = string.Format("{0}", ex.Message);
                    }
                }
                else
                {
                    retVal.Msg = "验证码错误";
                }
            }
            else
            {
                retVal.Msg = "参数为空";
            }
            ViewBag.Result = retVal;

            return View(user);
        }

        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        public virtual async Task<IActionResult> Logout()
        {
            try
            {
                this.UserSession.Clear();
            }
            catch { }

            try
            {
                await this.SignInManager.SignOutAsync();
            }
            catch { }

            return Redirect("~/Account/Login");
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public virtual async Task<IActionResult> ChangeMyPassword()
        {
            string oldPwd = Request.Form.GetString("OldPassword");
            string new1Pwd = Request.Form.GetString("New1Password");
            string new2Pwd = Request.Form.GetString("New2Password");
            if (string.Compare(new1Pwd, new2Pwd, false) == 0)
            {
                try
                {
                    var user = await this.UserManager.FindByIdAsync(this.GetUserId().ToString());
                    if (user != null)
                    {
                        var options = this.HttpContext.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions<Microsoft.AspNetCore.Identity.PasswordHasherOptions>)) as Microsoft.Extensions.Options.IOptions<Microsoft.AspNetCore.Identity.PasswordHasherOptions>;
                        if (options != null)
                        {
                            var passwordHasher = new Microsoft.AspNetCore.Identity.PasswordHasher<Admin.CYT369.Com.DAL.Domains.SysUser>(options);
                            user.PasswordHash = passwordHasher.HashPassword(user, new1Pwd);
                        }

                        if (Admin.CYT369.Com.DAL.Services.UserService.Instance.ChangeUserPassword(user))
                        {
                            return Ok();
                        }
                        else
                        {
                            return BadRequest("密码修改失败");
                        }
                    }
                    else
                    {
                        return BadRequest("找不到登录账户");
                    }
                }
                catch (Exception ex)
                {
                    Admin.CYT369.Com.DAL.Services.AppService.Instance.SaveAppLog("admin.cyt369.com", ex);
                    return BadRequest(ex.Message);
                }
            }
            else
            {
                return BadRequest("两次输入的密码不一致");
            }
        }

        /// <summary>
        /// 保存头像
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public virtual IActionResult SaveUserAvatar()
        {
            if (Request.Form.Files.Count > 0)
            {
                var file = Request.Form.Files[0];
                if (file.Length > 0)
                {
                    using (var stream = file.OpenReadStream())
                    {
                        int len = 0, total = 0;
                        var buffer = new byte[1024 * 4];

                        using (var fs = new System.IO.MemoryStream())
                        {
                            while ((len = stream.Read(buffer, 0, buffer.Length)) > 0 && total < file.Length)
                            {
                                fs.Write(buffer, 0, len);
                                total += len;
                            }

                            var avatar = "data:image/jpeg;base64," + Convert.ToBase64String(fs.ToArray());
                            if (Admin.CYT369.Com.DAL.Services.UserService.Instance.ChangeUserAvatar(this.GetUserId(), avatar))
                            {
                                return DefaultJson(new
                                {
                                    Result = true,
                                    Avatar = avatar
                                });
                            }
                        }

                        stream.Dispose();
                    }

                }
            }

            return DefaultJson(new
            {
                Result = false
            });
        }

        #region 验证码
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public virtual IActionResult GetCaptcha()
        {
            try
            {
                int CaptchaLen = 4;
                int codeW = 80;
                int codeH = 25;
                int fontSize = 16; Random rnd = new Random();
                //颜色列表，用于验证码、噪线、噪点
                Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
                //字体列表，用于验证码
                string[] font = { "Times New Roman", "Goudy Stout", "Viner Hand ITC", "Georgia", "Arial", "Comic Sans MS" };
                //验证码的字符集，去掉了一些容易混淆的字符

                //写入Session、验证码加密
                //WebHelper.WriteSession("session_verifycode", Md5Helper.MD5(chkCode.ToLower(), 16));
                //创建画布
                var bmp = new Bitmap(codeW, codeH);
                var g = Graphics.FromImage(bmp);
                g.Clear(Color.White);
                //画噪线
                var lineNum = rnd.Next(5);
                for (int i = 0; i < lineNum; i++)
                {
                    int x1 = rnd.Next(codeW);
                    int y1 = rnd.Next(codeH);
                    int x2 = rnd.Next(codeW);
                    int y2 = rnd.Next(codeH);
                    Color clr = color[rnd.Next(color.Length)];
                    g.DrawLine(new Pen(clr), x1, y1, x2, y2);
                }
                //画验证码字符串
                string chkCode = "";
                for (int i = 0; i < CaptchaLen; i++)
                {
                    string fnt = font[rnd.Next(font.Length)];
                    Font ft = new Font(fnt, fontSize);
                    Color clr = color[rnd.Next(color.Length)];

                    var ch = "a";
                    switch (rnd.Next(0, 100) % 3)
                    {
                        case 0:
                            do
                            {
                                ch = ((char)rnd.Next('a', 'z')).ToString();
                            } while (ch == "o" || ch == "l" || ch == "z");
                            break;

                        case 1:
                            do
                            {
                                ch = ((char)rnd.Next('A', 'Z')).ToString();
                            } while (ch == "O" || ch == "I" || ch == "Z");
                            break;

                        default:
                            ch = ((char)rnd.Next('0', '9')).ToString();
                            break;
                    }

                    chkCode += ch;
                    g.DrawString(ch, ft, new SolidBrush(clr), (float)i * (18 + rnd.Next(2)), (float)rnd.Next(5));
                }

                //将验证码图片写入内存流，并将其以 "image/Png" 格式输出
                var ms = new System.IO.MemoryStream();
                try
                {
                    var image = TwistImage(bmp, true, Next(1, 3), Next(4, 6));

                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    ms.Seek(0, System.IO.SeekOrigin.Begin);
                    //return ms.ToArray();
                    this.HttpContext.Session.Set(Admin.CYT369.Com.Utility.ConstStringClass.CaptchaCode, System.Text.Encoding.UTF8.GetBytes(chkCode));

                    return new FileStreamResult(ms, "image/png");
                }
                catch (Exception)
                {
                    return null;
                }
                finally
                {
                    g.Dispose();
                    bmp.Dispose();
                }
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        /// <summary>
        /// 正弦曲线Wave扭曲图片
        /// </summary>
        /// <param name="srcBmp">图片路径</param>
        /// <param name="bXDir">如果扭曲则选择为True</param>
        /// <param name="nMultValue">波形的幅度倍数，越大扭曲的程度越高,一般为3</param>
        /// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param>
        private System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
        {
            double PI = 6.283185307179586476925286766559;
            Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);
            Graphics graph = Graphics.FromImage(destBmp);
            graph.FillRectangle(new SolidBrush(Color.White), 0, 0, destBmp.Width, destBmp.Height);
            graph.Dispose();
            double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;
            for (int i = 0; i < destBmp.Width; i++)
            {
                for (int j = 0; j < destBmp.Height; j++)
                {
                    double dx = 0;
                    dx = bXDir ? (PI * (double)j) / dBaseAxisLen : (PI * (double)i) / dBaseAxisLen;
                    dx += dPhase;
                    double dy = Math.Sin(dx);
                    int nOldX = 0, nOldY = 0;
                    nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
                    nOldY = bXDir ? j : j + (int)(dy * dMultValue);

                    Color color = srcBmp.GetPixel(i, j);
                    if (nOldX >= 0 && nOldX < destBmp.Width && nOldY >= 0 && nOldY < destBmp.Height)
                    {
                        destBmp.SetPixel(nOldX, nOldY, color);
                    }
                }
            }
            srcBmp.Dispose();
            return destBmp;
        }

        /// <summary>
        /// 获得下一个随机数
        /// </summary>
        /// <param name="min">最小值</param>
        /// <param name="max">最大值</param>
        private int Next(int min, int max)
        {
            int value = Next2(max - min) + min;
            return value;
        }

        /// <summary>
        /// 获得下一个随机数
        /// </summary>
        /// <param name="max">最大值</param>
        private int Next2(int max)
        {
            var rand = new System.Security.Cryptography.RNGCryptoServiceProvider();
            byte[] randb = new byte[4];
            rand.GetBytes(randb);
            int value = BitConverter.ToInt32(randb, 0);
            value = value % (max + 1);
            if (value < 0) value = -value;
            return value;
        }
        #endregion
    }
}